/*
 * @Author: MrDotYan 2564217790@qq.com
 * @Date: 2024-08-26 10:41:26
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-24 17:05:09
 * @FilePath: /webServerAdmin/src/directives/modules/auth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * v-auth
 * 按钮权限指令
 */
import { PermissionSchema } from "@/schema";
import { useAuthStore } from "@/stores/modules/auth";
import { type Directive, type DirectiveBinding } from "vue";

function handlerPermission(arr?: Array<PermissionSchema>) {
  return arr?.map(ele => ele.permissionCode);
}

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    const authStore = useAuthStore();
    const roles = handlerPermission(authStore.authButtonListGet ?? []);
    if (value instanceof Array && value.length) {
      const hasPermission = value.every(item => roles?.includes(item));
      const hasAddPermission = value.every(item => item.toUpperCase().includes("ADD"));
      if (!hasPermission) {
        if (!hasAddPermission) {
          el.parentElement?.append("--");
        }
        el.remove();
      }
    } else {
      if (!roles?.includes(value)) {
        if (!value.toUpperCase().includes("ADD")) el.parentElement?.append("--");
        el.remove();
      }
    }
  }
};

export default auth;
